package com.zx.mes.rabbitmq.hyl.consumer;

import com.rabbitmq.client.Channel;
import com.zx.mes.rabbitmq.entity.Message;
import com.zx.mes.rabbitmq.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * Rabbitmq 消费端
 * @author huayunlong
 * @date 2018-8-6
 */
@Slf4j
@Component
public class RabbitReceiver {


    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "${long.rabbitmq.queue}",
                            durable ="${long.rabbitmq.queue.durable}"
                    ),
                    exchange = @Exchange(
                            value = "${long.rabbitmq.exchange}",
                            ignoreDeclarationExceptions = "${long.rabbitmq.exchange.ignoreDeclarationExceptions}",
                            durable = "${long.rabbitmq.exchange.durable}",
                            type = "${long.rabbitmq.exchange.type}"
                    ),
                    key ="${long.rabbitmq.key}"
            )
    )
    @RabbitHandler
    public void onMessage(@Payload Order message, Channel channel
            ,@Headers Map<String, Object> headers) throws IOException {
        log.info(message.toString());
        Long tag= (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        log.info(String.valueOf(tag) );
        /// 手动ACK
        channel.basicAck(tag,false);
    }

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "${long.rabbitmq.queue2}",
                            durable ="${long.rabbitmq.queue.durable2}"
                    ),
                    exchange = @Exchange(
                            value = "${long.rabbitmq.exchange2}",
                            ignoreDeclarationExceptions = "${long.rabbitmq.exchange.ignoreDeclarationExceptions2}",
                            durable = "${long.rabbitmq.exchange.durable2}",
                            type = "${long.rabbitmq.exchange.type2}"
                    ),
                    key ="${long.rabbitmq.key2}"
            )
    )
    @RabbitHandler
    public void onMessage2(@Payload Message<Order> message, Channel channel
            , @Headers Map<String, Object> headers) throws IOException {
        log.info(message.toString());
        Long tag= (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        log.info(String.valueOf(tag) );
        /// 手动ACK
        channel.basicAck(tag,false);
    }

}
